<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>layui</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="../../../static/font-awesome-4.7.0/css/font-awesome.min.css" >
	<link rel="stylesheet" href="../../../static/vui/css/vui.css">
	<script type="text/javascript" src="../../../static/js/jquery-1.9.1.min.js"></script>
	<script type="text/javascript" src="../../../static/layer/layer.js"></script>
	<script type="text/javascript" src="../../../static/laydate/laydate.js"></script>
	<script type="text/javascript" src="../../../static/js/common.js"></script>
    <script type="text/javascript" src="../../../static/vui/js/datagrid.js"></script>
	<script type="text/javascript" src="../../../static/vui/js/vui.js"></script>
</head>
<body>
<div id="formArea">
    
    <div class="ctx-title">
    	<div class="text"><b id="order_add_title">库存盘点</b></div>
    	<div class="buttons">
    		<button class="button hide" id="create" title="盘存时当页数据需及时保存"><span>保存</span></button>
            <button class="button hide" id="checkStart"><span>开始盘存</span></button>
            <button class="button hide" id="checkEnd"><span>结束盘存</span></button>
    		<button class="button" id="back"><span>历史盘存</span></button>
    	</div>
    </div>

	<table class="table">
		<tr>
			<td>
				<label class="label">仓库</label>
			</td>
			<td>
				<div id="storeId"></div>
			</td>
			<td>
				<label class="label">商品分类</label>
			</td>
			<td>
				<div id="productTypeId"></div>
			</td>
			<td>
				<label class="label required">盘点日期</label>
			</td>
			<td>
				<input type="text" class="input" name="splitProduct.date" readonly="readonly" id="splitProduct_date" autocomplete="off" placeholder="yyyy-MM-dd"/>
			</td>

		</tr>
		<tr>
			<td>
				<label class="label">商品名称</label>
			</td>
			<td>
				<input class="input" name="productName" autocomplete="off"/>
			</td>
			<td>
				<label class="label">商品编码</label>
			</td>
			<td>
				<input class="input" name="productCode" autocomplete="off"/>
			</td>
			<td>
				<label class="label">规格型号</label>
			</td>
			<td>
				<input class="input" name="productModel" autocomplete="off"/>
			</td>
			<td>
				<button class="button hide" id="query"><span>查询</span></button>
				<button class="button hide" id="reset"><span>重置</span></button>
			</td>

		</tr>
	</table>
	<div id="fixtable"></div>

</div>
<script>
    var params = app.getRequestParams();
    $(function(){
        
        if(params.view!=1){
            $('#checkStart').show();
        }
        
        layer.load();
        var url = app.BASE_API_URL+'storeCheck/stonePage';
        $('#query').click(function(){
            var queryParams = app.serializeForm();
            queryParams.storeCheckId = params.id;
            $("#fixtable").datagrid("reload",queryParams);
        });

        $('#reset').click(function(){
            $('#formArea input[type!="button"]').val('');
            $('#splitProduct_date').val(app.time2str(new Date().getTime()));
        });

        if(params.view==1){
            url = app.BASE_API_URL+'storeCheck/stoneHisPage';
        }else{
            app.request({
                url:'storeCheck/getStoneCheckCurrStatus',
                success:function (resp) {
                    if( resp.data == 1 ){
                        $('#order_add_title').html('库存盘点【盘存中】');
                        $('#create').show();
                        $('#checkEnd').show();
                        $('#checkStart').hide();
                        $('#query').show();
                        $('#reset').show();
                    }else if(resp.data==0){
                        $('#order_add_title b').html('库存盘点【未开始】');
                        $('#checkStart').show();
                    }else{
                        layer.alert('盘存状态异常，请重新刷新页面', {icon: 2,skin: 'layer-ext-moon'});
                    }
                }
            });
		}

		var numberText = params.view==1?"盘存时库存数量":"当前库存数量";

        $('#fixtable').datagrid({
			url:url,
			queryParams:{storeCheckId:params.id},
            columns:[
                {field:'productName',title:'商品名称',width:80},
                {field:'code',title:'商品编码',width:80},
                {field:'unitName',title:'库存单位',width:80,fixed:true},
                {field:'productTypeName',title:'商品分类',width:80},
                {field:'storeName',title:'所属仓库',width:80},
                {field:'number',title:numberText,width:80,n:'number',formatter:function (row) {
					if(params.view==1){
						return row.checkNumber - row.changeNumber;
					}else{
						return row.number;
					}
				}},
                {field:'checkNumber',title:'盘点数量',n:'number',width:80,editor:'decimal',end:function (row,value,colTd) {
                    if( value==null || value== undefined ){
                        value = "";
					}
					value = $.trim(value);
					if(isNaN(value)){
                        colTd.parent().find('.vui-table-cell[field="checkNumber"]').html('');
						return;
					}
					if( value.length>0 ){
                        colTd.parent().find('.vui-table-cell[field="changeNumber"]').html(app.sub(value,app.div(row.number,app.DIV)).replace('.00',''));
					}
				},formatter:function (row) {
					if( row.checkNumber==null || row.checkNumber== undefined  || row.checkNumber.length==0){
						return '';
					}else{
						return row.checkNumber;
					}
				}},
                {field:'changeNumber',title:'盈亏数量',n:'number',width:80,formatter:function (row) {
					if(params.view==1){
						return row.changeNumber;
					}else{
						if(row.checkNumber!=null || row.checkNumber!=undefined){
							return app.sub(row.checkNumber,row.number);
						}
					}
				}},
                {field:'checkPrice',title:'盈亏成本',n:'money',width:80,editor:'decimal'}
            ]
        });
        
        $('#storeId').combobox({
            width:240,noDefault:true,
            url:'store/select',
            name:'storeId',
            valueField:'id',
            textField:'name'
        });

        $('#productTypeId').search({
            name:'productTypeLogicalCode',
            click:function(){
                var index = layer.getFrameIndex(window.name);
                app.window(layer,{
                    title:'商品分类选择',
                    btn:[],
                    area: ['500px', '500px'],
                    content: '../../common/productype_tree.html?index=-1&searchId=productTypeId&idField=logicalCode'
                });
            }
        });
        
        $('#checkStart').click(function () {
            layer.confirm('盘存期间所有【变动库存的功能】将无法使用，确定开始盘存吗？', {icon: 3, title:'提示'}, function(index){
                var date = $('input[name="splitProduct.date"]').val();
                app.request({
                    url:'storeCheck/start',
                    data:{date:new Date(date).getTime()},
                    success:function (resp) {
                        if( resp.data && resp.data.id ){
                            layer.alert('开始盘存成功', {icon: 1,skin: 'layer-ext-moon'},function (index) {
                                location.href='./check_add.html?id='+resp.data.id;
                                layer.close(index);
                            });
                        }else if(resp.data==-1){
                            layer.alert('上次盘存未结束，开始盘存失败', {icon: 2,skin: 'layer-ext-moon'});
                        }else{
                            layer.alert('开始盘存失败，请联系管理员', {icon: 2,skin: 'layer-ext-moon'});
                            
                        }
                    }
                });
                layer.close(index);
            });
        });

        $('#checkEnd').click(function () {
            layer.confirm('确定结束盘存吗？', {icon: 3, title:'提示'}, function(index){
                
                app.request({
                    url:'storeCheck/end',
                    success:function (resp) {
                        if( resp.data && resp.data.customerId ){
                            layer.alert('结束盘存成功', {icon: 1,skin: 'layer-ext-moon'},function (index) {
                                location.href='./check_add.html';
                                layer.close(index);
                            });
                        }else if(resp.data==-1){
                            layer.alert('未开始盘存，结束盘存失败', {icon: 2,skin: 'layer-ext-moon'});
                        }else{
                            layer.alert('结束盘存失败，请联系管理员', {icon: 2,skin: 'layer-ext-moon'});
                        }
                    }
                });
                layer.close(index);
            });
        });

        $('#back').click(function () {
            location.href = './check_list.html';
        });

        $('#create').click(function () {
            if( !checkForm() ){
                return;
            }
			save();
        });

        laydate.render({
            elem: '#splitProduct_date',value:new Date(app.getServerTime())
        });

        layer.closeAll('loading');
    });

    //保存
    function save(){
		var checkDatas = getCheckData();
        if(checkDatas.result == -1){
            return;
        }
		if(checkDatas.flag){
            app.msg(layer,'保存成功');
            return;
		}
        app.request({
            url:'storeCheck/insert',
            data:checkDatas,
            success:function(resp){
                if( resp.result==0 ){
                    app.msg(layer,'操作成功',1);
                }else{
                    app.msg(layer,'操作失败【'+resp.data+'】',2);
                }
                app.closeLastWindow();
            }
        });
    }

    function getCheckData(){
        var details = {flag:true};
        var index = 0;
        
        var rowsEle = $('#fixtable .vui-table-row');
        for( var i=0 ; i<rowsEle.length ; i++ ){ 
            var rowEle = rowsEle.eq(i);
            var row = rowEle.data();
            var value = rowEle.find('.vui-table-cell[field="checkNumber"]').html();
            var checkPrice = rowEle.find('.vui-table-cell[field="checkPrice"]').html();
            
            if(value==null || $.trim(value).length==0){
                continue;
            }
            
            if(checkPrice==null || $.trim(checkPrice).length==0){
                app.message(layer,'商品【'+row.productName+'】未填写盈亏成本');
                return {result:-1};
            }
            
            if(app.mul(value,app.DIV)==row.checkNumber && app.mul(checkPrice,app.DIV)==row.checkPrice ){
                continue;
            }
            
            details.flag = false;
            
            details["details["+index+"].productId"] = row.productId;
            details["details["+index+"].unitId"] = row.unitId;
            details["details["+index+"].storeId"] = row.storeId;
            details["details["+index+"].companyId"] = row.companyId;
            details["details["+index+"].checkNumber"] = rowEle.find('div[field="checkNumber"]').html()*app.DIV;
            details["details["+index+"].changeNumber"] = rowEle.find('div[field="changeNumber"]').html()*app.DIV;
            details["details["+index+"].checkPrice"] = rowEle.find('div[field="checkPrice"]').html()*app.DIV;
            index++;
        }
        
        return details;
	}

    //表单检查
    function checkForm(){
        var checkOptions = [
            {type:'input',name:'splitProduct.date',verify:[{type:'required'}]}
        ];
        return app.checkForm(checkOptions);
    }

</script>
</body>
</html>